package interview.juc;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhangrongqing
 * @Date: 2020/5/22 9:11
 */
public class PrintAandB2 {

    private ReentrantLock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();
    Condition conditionB = lock.newCondition();

    private AtomicInteger countValue = new AtomicInteger(0);

    public void printA(){
        lock.lock();
        if(lock.isLocked()){
            try {
                if(countValue.get()%2==0){
                    conditionA.await();
                }
                System.out.println("A");
                countValue.addAndGet(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                conditionB.signal();
                lock.unlock();
            }
        }
    }

    public void printB(){
        lock.lock();
        if(lock.isLocked()){
            try {
                if(countValue.get()%2==1){
                    conditionB.await();
                }
                System.out.println("B");
                countValue.addAndGet(1);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                conditionA.signal();
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        PrintAandB2 task = new PrintAandB2();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for(int i = 0;i < 10;i++){
            executorService.submit(task::printA);
        }

        ExecutorService executorService2 = Executors.newFixedThreadPool(10);
        for(int i = 0;i < 10;i++){
            executorService2.submit(task::printB);
        }

        executorService.shutdown();
        executorService2.shutdown();
    }
}
